﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AlphaBeatSoundEngine
{
    public class NoPatternForGivenWordLengthException : Exception 
    {

    }

    public class MusicalWord
    {

        private MusicStyle _style;
        private Tone _fundamental;
        private MusicPattern _adjustedPattern;
        private String _word;

        public MusicPattern Pattern { get { return _adjustedPattern; } }
        public MusicStyle Style { get { return _style; } }
        public String Word { get { return _word; } }

        public MusicalWord(String word) 
        {
            _word = word;

            //getting style
            int stylesCount = MusicStyle.MusicStyles.Count;
            _style = MusicStyle.MusicStyles[GetNumberFromWord(stylesCount)];

            //getting fundamental
            _fundamental = (Tone)GetNumberFromWord(12);//There are 12 tones in music

            //getting pattern
            int patternsCount = _style.GetAvailablePatternCountForWordLength(_word.Length);
            if (patternsCount > 0)
            {
                MusicPattern basicPattern = _style.GetPatternByIndexForWordLength(_word.Length, GetNumberFromWord(patternsCount));
                //ajusting pattern with fundamental
                _adjustedPattern = basicPattern.GetAdjustedPatternWithFundamental(_fundamental);
            }
            else
            {
                throw new NoPatternForGivenWordLengthException();
            }
        }

        public MusicalWord(MusicStyle style, MusicPattern pattern, Tone fundamentale)
        {
            //if you try to fool me
            if (style.Name == pattern.Tones[0].Style.Name)
            {
                _style = style;
                _fundamental = fundamentale;
                _adjustedPattern = pattern.GetAdjustedPatternWithFundamental(fundamentale);
                _word = String.Empty;
                for (int i = 0; i < _adjustedPattern.Length; i++) { _word += (i+1).ToString(); }
                
            }
            else //well actually, you can't fool me, fool
            {
                throw new Exception("I see what you did, there...");
            }
        }

        private int GetNumberFromWord(int arrayCount)
        {
            char[] word = _word.ToCharArray();
            int result = 0;
            for (int i = 0; i < word.Length; i++)
            {
                result += (int)word[i] * i;
            }
            result %= arrayCount;

            return result;
        }

        public override string ToString()
        {
            return "[MusicalWord : Word : '" + _word + "' - Style : '" + _style + "' - Fundamental : '" + _fundamental.ToString() + "' - Ajusted Pattern : '" + _adjustedPattern.ToString() + "']";
        }

    }
}
